<template>
  <div class="markdown-editor-container">
    <!-- 工具栏 -->
    <div class="toolbar" v-show="showToolbar">
      <div class="toolbar-left">
        <el-button v-if="false" type="primary" @click="newDocument">
          <el-icon><Plus /></el-icon>
          新建
        </el-button>
        <el-button @click="saveContent" :loading="saving">
          <el-icon><Document /></el-icon>
          保存
        </el-button>
        <el-button @click="exportMarkdown">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
        <el-button @click="importFile">
          <el-icon><Upload /></el-icon>
          导入
        </el-button>
      </div>
      <div class="toolbar-center">
        <el-input
          v-if="isEditingTitle"
          v-model="documentTitle"
          size="small"
          @blur="finishEditTitle"
          @keyup.enter="finishEditTitle"
          @keyup.esc="cancelEditTitle"
          ref="titleInput"
          class="title-input"
        />
        <span 
          v-else 
          class="document-title clickable" 
          @click="startEditTitle"
        >
          {{ documentTitle }}
        </span>
        <el-tag v-if="hasUnsavedChanges" type="warning" size="small">未保存</el-tag>
      </div>
      <div class="toolbar-right">
        <el-button size="small" text @click="showToolbar = false">隐藏工具栏</el-button>
      </div>
    </div>

    <!-- 编辑器容器 -->
    <div class="editor-container">
      <div id="vditor" ref="vditorContainer" class="vditor-wrapper"></div>
    </div>

    <!-- 文件导入对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入文件" width="400px">
      <el-upload
        class="upload-demo"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        accept=".md,.txt"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传 .md 或 .txt 文件
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmImport">确认导入</el-button>
        </span>
      </template>
    </el-dialog>
    <el-button
      v-if="!showToolbar"
      class="toolbar-fab"
      type="primary"
      circle
      @click="showToolbar = true"
      :icon="Document"
      title="显示工具栏"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Download, Upload, UploadFilled, Plus } from '@element-plus/icons-vue'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { useRoute } from 'vue-router'
import { getModelDetailApi } from '../../../api/modelApi'
import { postDownloadFileFromFileServer } from '../../../api/http'
import { replaceFile } from '../../../api/fileUploadApi'
import { createFileWithContent } from '../../../util/fileUtils'
import { replaceFileUrl } from '../../../util/StringUtils'

// 响应式数据
const vditorContainer = ref<HTMLElement>()
const vditor = ref<Vditor>()
const saving = ref(false)
const importDialogVisible = ref(false)
const selectedFile = ref<File | null>(null)
const documentTitle = ref('新文档')
const hasUnsavedChanges = ref(false)
const isEditingTitle = ref(false)
const titleInput = ref<HTMLElement>()
const originalTitle = ref('新文档')
const showToolbar = ref(true)

const router = useRoute();
const fileId = ref<number>()
if(router.query.fileId) {
  fileId.value = parseInt(router.query.fileId as string);
}

const fileInfo = ref<any>({})
const loadMarkdown = async ()=>{
  const data = await getModelDetailApi(fileId.value as number, "id,name,url","document.file")
  fileInfo.value = data
  documentTitle.value = fileInfo.value.name
}

// 默认内容 - 完全空白的新文档
const defaultContent = ``

// 初始化 Vditor
const initVditor = (defaultContent:string) => {
  try {
    // 确保 DOM 元素存在
    const vditorElement = document.getElementById('vditor')
    if (!vditorElement) {
      console.error('Vditor 容器元素不存在')
      ElMessage.error('编辑器初始化失败：找不到容器元素')
      return
    }

    vditor.value = new Vditor('vditor', {
    height: '100%',
    mode: 'ir',
    toolbar: [
      'emoji', 'headings', 'bold', 'italic', 'strike', 'link', '|',
      'list', 'ordered-list', 'check', 'outdent', 'indent', '|',
      'quote', 'line', 'code', 'inline-code', 'insert-before', 'insert-after', '|',
      'upload', 'table', '|',
      'undo', 'redo', '|',
      'edit-mode', 'content-theme', 'code-theme', 'export', '|',
      'fullscreen', 'preview', 'help'
    ],
    cache: {
      enable: false
    },
    preview: {
      delay: 1000
    },
    upload: {
      accept: 'image/*,.mp3, .wav, .rar, .doc, .docx, .pdf, .txt, .md, .zip',
      url: '/api/upload',
      fieldName: 'file',
      success(editor: any, msg: string) {
        const res = JSON.parse(msg)
        if (res.code === 0) {
          editor.insertValue(`![图片](${res.data.url})`)
        } else {
          ElMessage.error('上传失败')
        }
      }
    },
    counter: {
      enable: true
    },
    theme: 'classic',
    icon: 'material',
    value: defaultContent,
    after: () => {
      // 编辑器初始化完成后的回调
      console.log('Vditor 初始化完成')
    }
  })
  } catch (error) {
    console.error('Vditor 初始化失败:', error)
    ElMessage.error('编辑器初始化失败，请刷新页面重试')
  }
}

// 新建文档
const newDocument = () => {
  if (!vditor.value) return
  
  ElMessageBox.confirm(
    '确定要创建新文档吗？当前内容将丢失。',
    '新建文档',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    vditor.value?.setValue('')
    documentTitle.value = '新文档'
    originalTitle.value = '新文档'
    hasUnsavedChanges.value = false
    isEditingTitle.value = false
    ElMessage.success('已创建新文档')
  }).catch(() => {
    // 用户取消
  })
}

// 保存内容
const saveContent = async () => {
  if (!vditor.value) return
  
  saving.value = true
  try {
    const file = createFileWithContent("test.md", vditor.value.getValue(), "text/markdown")
    replaceFile(replaceFileUrl(fileInfo.value.url) , file).then((res) => {
      hasUnsavedChanges.value = false
      ElMessage.success('文件保存成功')
    })
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

// 导出 Markdown
const exportMarkdown = () => {
  if (!vditor.value) return
  
  const content = vditor.value.getValue()
  const blob = new Blob([content], { type: 'text/markdown' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `markdown-export-${new Date().getTime()}.md`
  a.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('导出成功')
}

// 导入文件
const importFile = () => {
  importDialogVisible.value = true
}

// 处理文件选择
const handleFileChange = (file: any) => {
  selectedFile.value = file.raw
}

// 确认导入
const confirmImport = () => {
  if (!selectedFile.value || !vditor.value) {
    ElMessage.warning('请选择文件')
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    const content = e.target?.result as string
    vditor.value?.setValue(content)
    const fileName = selectedFile.value?.name || '导入的文档'
    documentTitle.value = fileName
    originalTitle.value = fileName
    hasUnsavedChanges.value = false
    isEditingTitle.value = false
    ElMessage.success('文件导入成功')
    importDialogVisible.value = false
    selectedFile.value = null
  }
  reader.readAsText(selectedFile.value)
}

// 这些函数已移除，因为不再需要预览模式和全屏功能

// 开始编辑标题
const startEditTitle = () => {
  isEditingTitle.value = true
  originalTitle.value = documentTitle.value
  nextTick(() => {
    titleInput.value?.focus()
  })
}

// 完成编辑标题
const finishEditTitle = () => {
  if (documentTitle.value.trim() === '') {
    documentTitle.value = originalTitle.value
  }
  isEditingTitle.value = false
}

// 取消编辑标题
const cancelEditTitle = () => {
  documentTitle.value = originalTitle.value
  isEditingTitle.value = false
}

// 监听键盘快捷键
const handleKeydown = (e: KeyboardEvent) => {
  if (e.ctrlKey || e.metaKey) {
    switch (e.key) {
      case 'n':
        e.preventDefault()
        newDocument()
        break
      case 's':
        e.preventDefault()
        saveContent()
        break
      case 'o':
        e.preventDefault()
        importFile()
        break
    }
  }
  
  // 标记为未保存状态
  if (!hasUnsavedChanges.value && vditor.value) {
    hasUnsavedChanges.value = true
  }
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    loadMarkdown().then(()=>{
       postDownloadFileFromFileServer(fileInfo.value.url, {}).then((res) => {
        res.data.text().then((text: string) => {
          initVditor(text)
        })
      });
    })
    
  })
  
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
  document.body.style.overflow = ''
  
  // 清理 Vditor 实例
  if (vditor.value) {
    vditor.value.destroy()
    vditor.value = undefined
  }
})

// 响应式数据监听已移除
</script>

<style scoped>
.markdown-editor-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.toolbar {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  align-items: center;
  padding: 12px 20px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
  justify-content: flex-start;
}

.toolbar-right {
  justify-content: flex-end;
}

.toolbar-center {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
  min-width: 0; /* 确保 flex 项目可以收缩 */
}

.document-title {
  font-weight: 500;
  color: #606266;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 300px;
}

.document-title.clickable {
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.document-title.clickable:hover {
  background-color: #f5f7fa;
}

.title-input {
  width: 200px;
  max-width: 300px;
  text-align: center;
}

.editor-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.toolbar-fab {
  position: fixed;
  right: 20px;
  top: 20px;
  z-index: 1000;
}

/* 全屏样式已移除 */

.vditor-wrapper {
  height: 100%;
  width: 100%;
}

.vditor-wrapper :deep(.vditor) {
  height: 100% !important;
}

.vditor-wrapper :deep(.vditor-toolbar) {
  border-bottom: 1px solid #e4e7ed;
}

.vditor-wrapper :deep(.vditor-ir),
.vditor-wrapper :deep(.vditor-sv),
.vditor-wrapper :deep(.vditor-wysiwyg) {
  height: calc(100% - 50px) !important;
}

.upload-demo {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    grid-template-columns: 1fr;
    gap: 12px;
    padding: 8px 12px;
  }
  
  .toolbar-left,
  .toolbar-right {
    justify-content: center;
  }
  
  .toolbar-center {
    order: -1; /* 在移动端将标题放在最上面 */
    margin-bottom: 8px;
  }
  
  .document-title {
    max-width: 100%;
  }
}
</style>
